<?php

namespace app\mobile\controller;

use think\Controller;

use think\Request;
use think\Session;
use \think\Db;

use app\api\model\User as UserModel;

use app\mobile\extra\phpqucode;
use app\common\library\wechat\WxPayTwo;
use app\common\library\wechat\WxPay;
use app\common\library\wechat\WeChatPay;
use app\common\library\wechat\WxpayService;
class Base2 extends Controller
{
	private $urlHeader = '';
	public $user;
	public function _initialize()
	{
        /*
        $user_agent = isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'';
        $isWechat = strpos($user_agent, 'MicroMessenger') !== false;
        if ($isWechat) {
            $this->wxllogin();
        }*/
    }

    public function wxllogin(){
        $request = Request::instance();
		$this->urlHeader = $request->domain();
		
		$request = Request::instance();
		Session::set('loginOkJumpUrl', $request->url(true));
		$openId = Session::get('openId');
		$this->user = Db::name('user')->where('open_id',$openId)->find();
		if(!$openId || !$this->user){
			//return $this->redirect('pagelogin/wxyesdiv');

			$appId = Config('appId');
			$appSecret = Config('appSecret');
			
			$request = Request::instance();
			
			if (!isset($_GET["code"])){
				$redirectUrl = $request->url(true);
				$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appId}&redirect_uri={$redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
				return $this->redirect($url);
			}
			else{
				$code = $request->param('code');
				// echo '<pre>';
				// print_r($code);
				// exit;
				
				// 根据code获取access_token和openid
				$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appId}&secret={$appSecret}&code={$code}&grant_type=authorization_code";
				$result = file_get_contents($url);
				$data = json_decode($result, true);
				// echo '<pre>';
				// print_r($data);
				// exit;
				
				// 获取用户信息
				$access_token = $data['access_token'];
				$openid = $data['openid'];
				$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
				$result = file_get_contents($url);
				$userInfo = json_decode($result, true);
				// echo '<pre>';
				// print_r($userInfo);
				// exit;
				
				if(isset($userInfo['openid']) && $userInfo['openid']!=''){
					// 先查询，如果有用户，直接跳转，如果无用户，先注册后再跳转---------------------
					$model = new UserModel;
					$indbArr = array(
						'wxappid' => Config('wxappid'),
						'channelSource' => 2,
						'open_id' => $userInfo['openid'],
						'nickName' => $userInfo['nickname'],
						'avatarUrl' => $userInfo['headimgurl'],
					);
					$resArr = $model->login44($indbArr);
					
					Session::set('openId', $userInfo['openid']);
					return $this->redirect(Session::get('loginOkJumpUrl'));
				}
				else{
					echo '微信网页授权登录失败!!!';
				}
			}
		}
    }
}